<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/6
 * Time: 14:22
 */

namespace app\index\domain;

use app\index\model\ErrorCode;
use app\system\model\UcenterMember;
use app\index\domain\BaseDomain;
use app\system\model\OAuth2Type;
use app\system\api\UcenterMemberApi;
use app\system\api\UserApi;
use app\system\api\UserLogApi;
use app\system\api\MemberFocusApi;
use app\system\model\BoyeActionConst;
use app\common\api\AccountApi;
use app\shop\api\MemberConfigApi;
use app\shop\api\RedEnvelopeApi;
use app\shop\api\WithdrawAccountApi;
use app\shop\model\WithdrawAccount;
use app\system\api\MemberApi;
use app\admin\api\SecurityCodeApi;
use app\admin\model\SecurityCode;
use app\admin\api\MessageApi;
use app\admin\model\Message;

class UserDomain extends BaseDomain
{
  protected $api_code = 'user';

  public function testMoney(){
    $this->checkVersion($this->api_ver);
    if(IS_POST) {
      addLog("User/testMoney", $_GET, $_POST, $this->client_id . "调用关注用户接口!");
      $uid   = $this->_post('uid',0,"uid无效!");
      $money = $this->_post('money',0,"money无效!");
      if($money<0) $money = -$money;
      $r = apiCall("shop/WalletApi/save",[['uid'=>$uid],['account_balance'=>$money]]);
      if(!$r['status']) $this->apiReturnErr($r['info']);
      else $this->apiReturnSuc('天降横财?');
    }
  }
  /**
   * 用户关注
   * @return [type] [description]
   */
  public function focus(){
    $this->checkVersion($this->api_ver);
    if(IS_POST) {
      addLog("User/focus", $_GET, $_POST, $this->client_id . "调用关注用户接口!");
      $uid       = $this->_post('uid',0,"uid无效!");
      $focus_uid = $this->_post('focus_uid',0,"focus_uid无效!");
      $value     = $this->_post('value',1);
      $value     = intval($value);
      if(!in_array($value,[0,1])) $this-> apiReturnErr('value非法');
      //用户是否存在
      $r = apiCall(MemberApi::QUERY_NO_PAGING,['`uid`='.$uid.' or `uid`='.$focus_uid]);
      if(!$r['status']) $this->apiReturnErr($r['info']);
      if($uid == $focus_uid)  $this->apiReturnErr('不允许用户关注自己');
      if(2 != count($r['info'])) $this->apiReturnErr('uid 或 focus_uid 不存在');
      //是否关注过
      $r = apiCall(MemberFocusApi::GET_INFO,[['uid'=>$uid,'focus_uid'=>$focus_uid]]);
      if(!$r['status']) $this->apiReturnErr($r['info']);
      if(empty($r['info'])){
        //没关注
        if(0 === $value) $this->apiReturnErr('您并未关注此用户');
        $map = [
          'uid'        =>$uid,
          'focus_uid'  =>$focus_uid,
          'focus_time' =>NOW_TIME,
        ];
        $r = apiCall(MemberFocusApi::ADD,[$map]);
        if(!$r['status']) $this->apiReturnErr($r['info']);
        // 推送系统消息
        $entity = [
            'from_id' =>0,
            'title'   =>Message::MESSAGE_BBS,
            'content' =>'被人关注了，好开森',
            'summary' =>'新粉丝',
            'record'  => false,
            'extra'   =>'', //消息记录中的
        ];
        $after_open = ['type'=>'go_activity','param'=>Message::MESSAGE_BBS_ACTIVITY,'extra'=>['type'=>3]];
        $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,[Message::MESSAGE_BBS,$entity,$focus_uid,false,$after_open]);
        if(!$r['status']) $this->apiReturnSuc($r['info']);
        else $this->apiReturnSuc('关注成功');
      }else{
        //已关注
        if(1 === $value) $this->apiReturnErr('您已关注此用户');
        $map = [
          'uid'       =>$uid,
          'focus_uid' =>$focus_uid,
        ];
        $r = apiCall(MemberFocusApi::DELETE,[$map]);
        if(!$r['status']) $this->apiReturnErr($r['info']);
        $this->apiReturnSuc('取消关注成功');
      }
    }
  }
//
//    /**
//     * 微信用户更换手机号
//     */
//    public function weixinChangePhone(){
//        $this->checkVersion(100);
//        if(IS_POST) {
//            addLog("User/changePhone", $_GET, $_POST, $this->client_id . "调用用户手机更换接口!");
//            $ori_mobile = $this->_post('ori_mobile','','原手机号无效');
//            $uid = $this->_post('uid', 0,"用户ID无效!");
//            $code = $this->_post('code', '',"密码无效");
//            $mobile = $this->_post('mobile', '',"新手机无效");//新手机
//
//            if($ori_mobile == $mobile){
//                $this -> apiReturnErr('手机号码未更改');
//            }
//
//
//            $type = SecurityCodeModel::TYPE_FOR_CHANGE_NEW_PHONE;
//            //1. 验证－验证码
//            $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE, array($code, $mobile, $type));
//
//            if (!$result['status'] || empty($result['info'])) {
//                $this->apiReturnErr("验证码错误!",'10');
//            }
//
//            //2. 验证新手机是否已经被其它账户绑定过
//            $result = apiCall(UserApi::FIND,array(array('mobile'=>$mobile)));
//            if($result['status'] && is_array($result['info'])){
//                $this->apiReturnErr("无法绑定该手机号，因为已经绑定其它账号!",'11');
//            }
//
//            //3. 验证-密码是否有限
//            $result = apiCall(UserApi::FIND,array(array('id'=>$uid)));
//
//            if (!$result['status']) {
//                $this->apiReturnErr($result['info'],'12');
//            }
//            if($ori_mobile != $result['info']['mobile']){
//                $this->apiReturnErr("原手机号有误!".$ori_mobile,'13');
//            }
//
//            $this->updateMobile($uid,$mobile);
//
//            $this->apiReturnSuc("更换成功!");
//
//        }
//
//    }
//
   /**
    * 更换手机号
    */
   public function changePhone(){

       if(IS_POST) {
           $this->checkVersion($this->api_ver);
           addLog("User/changePhone", $_GET, $_POST, $this->client_id . "调用用户手机更换接口!");
           $password = $this->_post('password','','密码参数缺失');
           $uid = $this->_post('uid', 0,"用户ID无效!");
           $code = $this->_post('code', '',"验证码无效");
           $mobile = $this->_post('mobile', '',"新手机无效");//新手机


           $type = SecurityCode::TYPE_FOR_CHANGE_NEW_PHONE;
           //1. 验证－验证码
           $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE, [$code, $mobile, $type]);

           if (!$result['status'] || empty($result['info'])) {
               $this->apiReturnErr("验证码错误!",'10');
           }

           //2. 验证新手机是否已经被其它账户绑定过
           $result = apiCall(UserApi::FIND,[['mobile'=>$mobile]]);
           if($result['status'] && is_array($result['info'])){
               $this->apiReturnErr("无法绑定该手机号，因为已经绑定其它账号!",'11');
           }

           //3. 验证-密码是否有限
           $result = apiCall(UserApi::FIND,[['id'=>$uid]]);
           $mdPsw = itboye_ucenter_md5($password,UC_AUTH_KEY);

           if (!$result['status']) {
               $this->apiReturnErr($result['info'],'12');
           }
           if($mdPsw != $result['info']['password']){
               $this->apiReturnErr("密码错误!".$mdPsw,'13');
           }

           $this->updateMobile($uid,$mobile);

           $this->apiReturnSuc("更换成功!");

       }

   }

   /**
    * 微信登陆用 - 绑定手机并设置密码
    */
   public function bind(){
       if(IS_POST){
           $this->checkVersion($this->api_ver);
           addLog("User/bind",$_GET,$_POST,$this->client_id."调用用户手机绑定接口!");
           $username = $this->_post('mobile','',"手机不能为空");//传入一般为手机号
           $uid = $this->_post('uid',0,"uid为空");
           $code = $this->_post('code','',"验证码错误");
           $password = $this -> _post('password','','密码不能为空');

           if(strlen($password) < 6 || strlen($password) > 64){
               $this -> apiReturnErr('密码的长度必须大于6小于64');
           }
           if(!preg_match("/^[0-9a-zA-Z\\\\,.?><;:!@#$%^&*()_+-=\[\]\{\}\|]{6,64}$/",$password)){
             $this -> apiReturnErr('密码只能包含数字、英文字母以及如下字符 \,.?><;:!@#$%^&*()_+-=!');
           }
           $type = SecurityCode::TYPE_FOR_NEW_BIND_PHONE;

           $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$username,$type));

           if (!$result['status'] || empty($result['info'])) {
               $this->apiReturnErr("验证码错误!");
           }

           //验证通过，表明手机可用

           $result = apiCall(UserApi::FIND,array(array('mobile'=>$username)));
           if($result['status'] && is_array($result['info'])){
               $this->apiReturnErr("该手机号已绑定另外一个账号!");
           }

           $password = think_ucenter_md5($password, UC_AUTH_KEY);
           $entity = array(
               'password' => $password,
           );
           $result = apiCall(UserApi::SAVE_BY_ID,array($uid,$entity));
           if(!$result['status']){
               $this -> apiReturnErr($result['info']);
           }

           $this->updateMobile($uid,$username);

       }

       $this->apiReturnErr("非法请求!");

   }

   /**
    * 更新密码
    */
   public function updatePsw(){
       $this->checkVersion($this->api_ver);
       addLog("User/updatePsw",$_GET,$_POST,'应用'.$this->client_id."调用更新密码接口");
       //
       if(IS_POST){

           $id     = $this->_post('uid','','用户ID缺失');
           $old_psw = $this->_post('old_psw','','旧密码缺失');
           $psw     = $this->_post('psw','','新密码缺失');

           if(!intval($id)) $this->apiReturnErr("用户ID格式错误!");
           $result = apiCall(UserApi::FIND,[['id'=>$id]]);
           if (!$result['status'] && empty($result['info'])) {
               $this->apiReturnErr("用户账户非法!");
           }
           //$code = $this->_post('code','',"验证码参数缺失");
           /*if(empty($old_psw) && empty($code)){
               $this->apiReturnErr("验证参数缺失!");
           }*/
           //验证码存在时，排除密码
           /*if(!empty($code)){
               $old_psw = '';
           }*/
           //$old_psw = base64_decode($old_psw);
           //$psw = base64_decode($psw);

           // $type = $this->getUsernameType($username);
           $type = $this->getUsernameType($result['info']['username']);
           // $result = array('status');
           // if($type == UcenterMember::ACCOUNT_TYPE_MOBILE){
           //     $result = apiCall(UserApi::FIND,array(array('mobile'=>$username)));
           // }elseif($type == UcenterMember::ACCOUNT_TYPE_USERNAME){
           //     $result = apiCall(UserApi::FIND,array(array('username'=>$username)));
           // }else{
           //     $this->apiReturnErr("参数非法!");
           // }

           // if (!$result['status'] && empty($result['info'])) {
           //     $this->apiReturnErr("用户登录账户非法!");
           // }
           // $id = $result['info']['id'];

          // addLog("id",$id,$psw,"");
           //**************检测是否合法用户，要修改密码，必须确保用户身份有权限******
          /* if(!empty($code)){
               $type = SecurityCodeModel::TYPE_FOR_UPDATE_PSW; //

               $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$username,$type));
               if(!$result['status']){
                   $this->apiReturnErr("验证失败");
               }
           }elseif(!empty($old_psw)) {
               if ($result['info']['password'] != think_ucenter_md5($old_psw, UC_AUTH_KEY)) {
                   $this->apiReturnErr("原密码错误!");
               }
           }*/

           if(!empty($old_psw)) {
               if ($result['info']['password'] != think_ucenter_md5($old_psw, UC_AUTH_KEY)) {
                   $this->apiReturnErr("原密码错误!");
               }
           }

           //**************************************************************
           if(strlen($psw) < 6){
               $this->apiReturnErr("密码必须大于6位长度!");
           }
           addLog("User/updatePsw",$_GET,$_POST,'应用'.$this->client_id."调用更新密码接口");
           $result = apiCall(UserApi::UPDATEPWD,[$id,$psw]);
           //记录成功更新密码的日志
           action_log(BoyeActionConst::API_USER_UPADTE_PSW, "member", $id,$this->client_id);

           if (!$result['status']) {
               $this->apiReturnErr("更新密码失败!".$result['info']);
           }

           $this->apiReturnSuc("更新密码成功!");

       }else{
           $this->apiReturnErr("更新密码失败!");
       }
   }

    /**
     * POST: 登录
     * @internal param post.username
     * @internal param post.password
     */
    public function login()
    {
        $this->checkVersion($this->api_ver);
        addLog("LOGIN",$_GET,$_POST,"[接口调用开始]");

        $username = $this->_post("username","","用户名缺失");
        $password = $this->_post("password","","密码缺失");
        $type = $this->getUsernameType($username);
        $device_type = $this->_post("password","app");

      addLog("LOGIN3",$_GET,$_POST,"[接口调用开始]");

      $notes = "应用" . $this->client_id . ":[用户" . $username . "],调用登录接口,密码：" . $password.'用户类型:'.$type;

      addLog("User/login", $_GET, $_POST, $notes);

      //for test
      // $result = apiCall(UcenterMemberApi::GET_INFO,array(array('username'=>$username,'password'=>$password)));

      // if($result['status']){
      //     if(($result['info']==[])){
      //         $this->apiReturnErr('用户名密码错误或该用户不存在');
      //     }else{
      //         $this->apiReturnSuc($result['info']);
      //     }
      // }else{
      //     $this->apiReturnErr($result['info']);
      // }
      // 测试用
      // sleep(3);
      // $this->apiReturnSuc($result['info']);

      $result = apiCall(AccountApi::LOGIN, array($username, $password, $type, $device_type));

      if ($result['status']) {
          $uid = $result['info'];

          $session_id = (new UcenterMember())->addLoginSession($uid, $device_type);
          // return $this->apiReturnSuc($uid);
          $result = apiCall(AccountApi::GET_INFO, array($uid));
          // return $this->apiReturnSuc($result);

          if(!$result['status']){
              $this->apiReturnErr($result['info']);
          }

          action_log(BoyeActionConst::API_USER_LOGIN, "member", $uid, $uid);

          //判断是否在
          $result['info']['login_session_code'] = $session_id;

          $this->apiReturnSuc($result['info']);

      } else {
          $this->apiReturnErr($result['info']);
      }

    }

    public function loginBySession()
    {
        $this->checkVersion($this->api_ver);

        $uid = $this->_post('uid', '', '用户id缺失');
        $login_session = $this->_post('login_session', '', '登录code缺失');

        $notes = "应用" . $this->client_id . ":[用户id" . $uid . "],调用session登录接口,session：" . $login_session;

        addLog("User/loginByCOde", $_GET, $_POST, $notes);

        $result = apiCall(AccountApi::LOGIN_BY_SESSION, [$uid, $login_session]);

        if ($result['status']) {
            $result = apiCall(AccountApi::GET_INFO, array($uid));

            if(!$result['status']){
                $this->apiReturnErr($result['info']);
            }

            action_log(BoyeActionConst::API_USER_LOGIN, "member", $uid, $uid);

            //判断是否在

            $this->apiReturnSuc(true);

        } else {
            $this->apiReturnSuc(false);
        }

    }

    /**
     * POST: 注册
     * username 用户名
     * password 密码
     * mobile 手机
     * realname真实姓名
     * email 电子邮箱
     * idnumber身份证号
     * birthday生日
     * @param $str
     * @return int
     */
   public function register()
   {
     $this->checkVersion(101);
     $notes = "应用" . $this->client_id . "，调用注册接口";

     addLog("User/register", $_GET, $_POST, $notes);

     if (IS_POST) {

      $type     = $this->_post("reg_type", 3);
      $username = $this->_post("username", "","用户名缺失");
      $code     = $this->_post("code","");
      $from     = $this->_post("from", 0);
      $error    = $this->isLegal($type,$username,$from);
      $password = $this->_post("password","","密码缺失");

      //可选参数
      $email       = $this->_post("email", '');
      $invite_code = $this->_post("invite_code", '');
      $invite_code = strtoupper($invite_code);
      $sex         = intval($this->_post("sex", 0));
      //查询邀请用户UID
      if($invite_code){
         $map = [
             'idcode' => $invite_code,
         ];
         $result = apiCall(MemberConfigApi::GET_INFO,[$map]);
         if($result['status']){
            // if(empty($result['info'])) $this->apiReturnErr('邀请码错误');
            // $invite_id = $result['info']['uid'];
            if(empty($result['info'])){
                $invite_id = 0;
            }else{
                $invite_id = $result['info']['uid'];
            }
         }else{
             $this -> apiReturnErr($result['info']);
         }
      }else{
        $invite_id = 0;
      }
      // $this->apiReturnErr($invite_id);
      if (!($error === false)) {
        $this->apiReturnErr($error,ErrorCode::Invalid_Parameter);
      }
      $mobile = "";
      $idcode = "";

      if($type == UcenterMember::ACCOUNT_TYPE_MOBILE){
        // if($code){
        //  //验证码
        // }
        $mobile = $username;
        //验证码验证
        $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,array($code,$mobile,SecurityCode::TYPE_FOR_REGISTER));
        if(!$result['status']){
           $this->apiReturnErr($result['info']);
        }

        $username = 'M'.time();//$mobile;
        $idcode = getIDCode($mobile,'M');
      }
      $entity = [
        'username'  => $username,
        'password'  => $password,
        'from'      => $from,
        'mobile'    => $mobile,
        'realname'  => '',
        'nickname'  => $username,
        'email'     => $email,
        'idnumber'  => '',
        'birthday'  => NOW_TIME,
        'idcode'    => $idcode,
        'type'      => $type,
        'invite_id' => $invite_id,
        'sex'       => $sex,
      ];

      $trans = new \think\model\Adv();
      $trans->startTrans();
      $result = apiCall(AccountApi::REGISTER, [$entity]);

      if ($result['status']) {
        $arr  = [];
        $flag = 0;
        $uid  = $result['info'];
        $arr['uid'] = $uid;
        //注册红包
        $result = apiCall(RedEnvelopeApi::REG_ADD,[$uid]);
        if(!$result['status']) $flag = 1;

        //+score  +exp
        $result = apiCall(UserLogApi::REGISTER,[$uid,$invite_id]);
        if(!$result['status']) $this ->apiReturnErr($result['info']);
        $arr['msg'] = $result['info'];
        if($flag == 1){
          $arr['msg']['err'][] = "注册红包发放失败,请联系管理员获取!";
        }else{
          $arr['msg']['suc'][] = "注册红包发放";
        }
        $trans->commit();
        $this ->apiReturnSuc($arr);
      } else {
        $trans->rollback();
        $this->apiReturnErr($result['info']);
      }
    } else {
       $this->apiReturnErr("只支持POST请求!");
    }

  }
  /**
  * 手机验证码登陆 未注册则直接注册一个手机账号
  * @return [type] [description]
  */
  public function loginByCode(){

    if(IS_POST){
      $this->checkVersion(101);
      addLog("User/loginByCode",$_GET,$_POST,$this->client_id."调用用户手机验证码登录接口");

      $mobile = $this -> _post('mobile','','手机号缺失');
      $code   = $this -> _post('code','','验证码缺失');

      $type   = SecurityCode::TYPE_FOR_LOGIN;
      $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,[$code,$mobile,$type]);
      $device_type = $_POST['app_type'];

      if($result['status']) {
        $result = apiCall(UserApi::FIND,[['mobile'=>$mobile]]);
        if(!$result['status'])  $this -> apiReturnErr($result['info']);
        if(empty($result['info'])){
          // trace('手机未注册');
          // $this -> apiReturnErr("该手机未注册！");

          //注册手机账号
          $username = 'M'.$mobile;
          $idcode   = getIDCode($mobile,'M');
          $entity = [
             'username'  => $username,
             'password'  => $mobile,//
             'from'      => 0,
             'mobile'    => $mobile,
             'realname'  => '',
             'nickname'  => $username,
             'email'     => '',
             'idnumber'  => '',
             'birthday'  => NOW_TIME,
             'idcode'    => $idcode,
             'type'      => 3,
             'invite_id' => '',
             'sex'       => 0,
          ];
          $result = apiCall(AccountApi::REGISTER, [$entity]);
          if ($result['status']) {
            $flag = 0;
            // 注册红包
            $uid = $result['info'];
            $result = apiCall(RedEnvelopeApi::REG_ADD,[$uid]);
            if(!$result['status']) $flag = 1;
            //+score  +exp
            $result = apiCall(UserLogApi::REGISTER,[$uid,0]);
            if(!$result['status']) $this ->apiReturnErr($result['info']);
            $arr = [];
            $arr['msg']   = $result['info'];
            $arr['extra'] = '自动注册成功,密码为手机号码,请尽快修改密码!';
            if($flag == 1){
              $arr['msg']['err'][] = "注册红包发放失败,请联系管理员获取!";
            }else{
              $arr['msg']['suc'][] = "注册红包发放";
            }

            $session_id = (new UcenterMember())->addLoginSession($uid, $device_type);

            $result = apiCall(AccountApi::GET_INFO, [$uid]);
            $result['info']['login_session_code'] = $session_id;
            //user action api_user_login
            action_log(BoyeActionConst::API_USER_LOGIN, "member", $uid, $uid);
            $result['info']['msg']   = $arr['msg'];
            $result['info']['extra'] = $arr['extra'];
            $this->apiReturnSuc($result['info']);
          }else{
            $this->apiReturnErr($result['info']);
          }
        }else{
          //trace('手机已注册');
          $uid = $result['info']['id'];
          $result = apiCall(AccountApi::GET_INFO, [$uid]);

          //user action api_user_login
          action_log(BoyeActionConst::API_USER_LOGIN, "member", $uid, $uid);
          $this->apiReturnSuc($result['info']);
        }
      }else{
        $this -> apiReturnErr($result['info']);
      }

    }
  }
   /**
    * 用户信息更新
    */
   public function update()
   {
      $this->checkVersion($this->api_ver);
      $notes = "应用" . $this->client_id . "，调用用户更新接口";
      addLog("User/update", $_GET, $_POST, $notes);

      if (IS_POST) {
           $uid = $this->_post('uid', 0,'用户ID为正整数');

           if($uid <= 0){
               $this->apiReturnErr("用户ID非法!");
           }

           $mobile   = $this->_post("mobile", "");
           $realname = $this->_post("realname", "");
           $email    = $this->_post("email", "");
           $idnumber = $this->_post("idnumber", "");
           // $alipay   = $this->_post("alipay", "");
           $birthday = strtotime($this->_post("birthday", 0));
           $nickname = $this->_post("nickname", "");
           $sex      = $this->_post("sex", "");
           $qq       = $this->_post("qq", "");
           // $head     = $this->_post("head", "");
           $sign     = $this->_post("sign","");   //个性签名

           $entity = [];
           if($sex!="")      $entity['sex'] = $sex;
           // if(!empty($head)) $entity['head'] = $head;
           if(!empty($qq))       $entity['qq']       = $qq;
           if(!empty($birthday)) $entity['birthday'] = $birthday;
           if(!empty($idnumber)) $entity['idnumber'] = $idnumber;
           if(!empty($email))    $entity['email']    = $email;
           if(!empty($realname)) $entity['realname'] = $realname;
           if(!empty($nickname)) $entity['nickname'] = $nickname;
           if(!empty($mobile))   $entity['mobile']   = $mobile;
           if(!empty($sign))     $entity['sign']     = $sign;
           // if(!empty($alipay))   $entity['alipay']   = $alipay;

           $r = apiCall(AccountApi::UPDATE, array($uid, $entity));
           if (!$r['status']) $this->apiReturnErr($r['info']);
           //刷新用户缓存
           flushUinfo($uid);
           $this->apiReturnSuc("操作成功！");
      }
   }

  /**
  *绑定提现账号
  */
  public function bindWithdraw()
  {
    $this->checkVersion(101);
    $notes = "应用" . $this->client_id . "，调用绑定支付宝接口";
    addLog("User/bindAlipay", $_GET, $_POST, $notes);

    if (IS_POST) {
        $mobile       = $this->_post('mobile', 0,'mobile缺失');
        $code         = $this->_post('code', '','code缺失');
        $account      = $this->_post('account', '','account缺失');
        $account_type = $this->_post('account_type',''); //1:支付宝
        $id           = $this->_post('uid', 0,'UID缺失');
        $realname     = $this->_post('realname','','realname缺失');
        if(!intval($id)) $this->apiReturnErr("用户ID格式错误!");
        if(!$account_type) $account_type = 1;
        if(1 !== intval($account_type)) $this->apiReturnErr("账号类型错误，暂只支持支付宝!");

        $result = apiCall(UserApi::FIND,[['id'=>$id]]);
        if (!$result['status'] && empty($result['info'])) {
           $this->apiReturnErr("用户账户非法!");
        }
        if($result['info']['mobile'] !== $mobile) $this->apiReturnErr('用户手机号不匹配');
        $r  = apiCall(MemberApi::GET_INFO,[['uid'=>$id]]);
        if (!$result['status'] && empty($result['info'])) {
           $this->apiReturnErr("用户账户非法!");
        }
        if($r['info']['realname'] != $realname){
          $r = apiCall(MemberApi::SAVE,[['uid'=>$id],['realname'=>$realname]]);
          if(!$r['status']) $this->apiReturnErr($r['info']);
        }
        $type   = SecurityCode::TYPE_FOR_BIND_ALIPAY;
        $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,[$code,$mobile,$type]);
        if ($result['status']==false) $this->apiReturnErr("验证码错误");
        //更新用户账号
        $r = apiCall(WithdrawAccountApi::GET_INFO,[['uid'=>$id,'account_type'=>$account_type]]);
        if(!$r['status']) $this->apiReturnErr($r['info']);
        if(empty($r['info'])){
          //add
          $map = [
           'uid'          =>$id,
           'account'      =>$account,
           'account_type' =>$account_type,
           'create_time'  =>time(),
           'valid_status' =>WithdrawAccount::PASS,
           'extra'        =>''
          ];
          $r = apiCall(WithdrawAccountApi::ADD,[$map]);
          if(!$r['status']) $this->apiReturnErr($r['info']);
          $this->apiReturnSuc('申请成功，请等待审核');
        }else{
          $status = intval($r['info']['valid_status']);
          if(WithdrawAccount::WAIT === $status){
            $this->apiReturnErr('账号审核中，请等待');
          }else{
            $map = [
              'account'=>$alipay,
              'account_type'=>$alipay_type,
              'valid_status'=>WithdrawAccount::PASS,
            ];
            $r = apiCall(WithdrawAccountApi::SAVE,[['uid'=>$id],$map]);
            if(!$r['status']) $this->apiReturnErr($r['info']);
            $this->apiReturnSuc('申请成功，请等待审核');
          }
        }
    }
  }
  /**
   *找回密码
  */
  public function findPswByMobile()
  {
    $this->checkVersion($this->api_ver);
    $notes = "应用" . $this->client_id . "，调用手机找回密码接口";
    addLog("User/findPswByMobile", $_GET, $_POST, $notes);

    if (IS_POST) {
      $mobile = $this->_post('mobile', 0);
      $code   = $this->_post('code', '');
      $psw    = $this->_post('psw', '');

        // $id     = $this->_post('uid', 0);
        // if(!intval($id)) $this->apiReturnErr("用户ID格式错误!");

        // $result = apiCall(UserApi::FIND,[['id'=>$id]]);
        // if (!$result['status'] && empty($result['info'])) {
        //    $this->apiReturnErr("用户账户非法!");
        // }
        // if($result['info']['mobile'] !== $mobile) $this->apiReturnErr('绑定手机号错误');

        $type   = SecurityCode::TYPE_FOR_UPDATE_PSW;
        $result = apiCall(SecurityCodeApi::IS_LEGAL_CODE,[$code,$mobile,$type]);
        if ($result['status']==false) $this->apiReturnErr("验证码错误");

        $result = apiCall(UserApi::FIND, array(array('mobile' => $mobile)));
        $id = $result['info']['id'];

        addLog("id", $id, $psw, "");

        $result = apiCall(UserApi::UPDATEPWD, [$id, $psw]);
        //记录成功更新密码的日志
        action_log(BoyeActionConst::API_USER_UPADTE_PSW, "member", $id, $this->client_id);

        if (!$result['status']) $this->apiReturnErr("更新密码失败!" . $result['info']);
        $this->apiReturnSuc("更新密码成功!");

      } else {
           $this->apiReturnErr("更新密码失败!");
    }
  }
//
//    /**
//     * 用户地址添加
//     */
//    public function addressAdd(){
//
//        $notes = "应用" . $this->client_id . "，调用用户地址添加接口";
//
//        addLog("User/addressAdd", $_GET, $_POST, $notes);
//
//        $this->checkVersion(100);
//
//        if(IS_POST){
//
//            $mobile = $this->_post('mobile','','用户手机缺失');
//            $provinceid = $this->_post('provinceid','','省缺失');
//            $cityid = $this->_post('cityid','','市缺失');
//            $areaid = $this->_post('areaid','','区缺失');
//
//            //可选参数
//            $contactname = $this->_post('contactname',' ');
//
//            //查询该手机号注册的帐号ID
//            $result = apiCall(UserApi::FIND, array(array('mobile' => $mobile)));
//            if($result['status']){
//                if(empty($result['info'])){
//                    $this->apiReturnErr('该手机号未注册');
//                }else{
//                    $uid = $result['info']['id'];
//                }
//            }else{
//                $this->apiReturnErr($result['info']);
//            }
//
//            //根据省城市代码查询 省
//            $result = apiCall(ProvinceApi::GET_INFO,array(array('provinceID' => $provinceid)));
//            if(!empty($result['info'])){
//                $province = $result['info']['province'];
//            }else{
//                $province = ' ';
//            }
//
//
//            //根据省城市代码查询 市
//            $result = apiCall(CityApi::GET_INFO,array(array('cityID' => $cityid)));
//            if(!empty($result['info'])){
//                $city = $result['info']['city'];
//            }else{
//                $city = ' ';
//            }
//            //根据省城市代码查询 市
//            $result = apiCall(AreaApi::GET_INFO,array(array('areaID' => $areaid)));
//            if(!empty($result['info'])){
//                $area = $result['info']['area'];
//            }else{
//                $area = ' ';
//            }
//
//            //身份证
//            $result = apiCall(MemberApi::GET_INFO,array(array('uid' => $uid)));
//            if(!empty($result['info'])){
//                $idnumber = $result['info']['idnumber'];
//            }else{
//                $idnumber = ' ';
//            }
//
//            //保存地址信息
//            $entity = array(
//                'uid'=>$uid,
//                'country'=>'中国',
//                'city'=>$city,
//                'province'=>$province,
//                'detailinfo'=>$province.$city.$area,
//                'area'=>$area,
//                'wxno'=>' ',
//                'areaid'=>$areaid,
//                'postal_code'=>0,
//                'id_card'=>$idnumber,
//                'cityid'=>$cityid,
//                'provinceid'=>$provinceid,
//                'contactname'=>$contactname,
//                'mobile'=>$mobile
//            );
//
//            //$this->apiReturnErr($entity);
//            $result = apiCall(AddressApi::ADD,array($entity));
//
//            if ($result['status']) {
//                $this->apiReturnSuc('添加成功');
//            } else {
//                $this->apiReturnErr($result['info']);
//            }
//
//        }else{
//            $this->apiReturnErr("只支持POST请求!");
//        }
//
//    }
//
//    /**
//     * 用户地址查询
//     */
//    public function addressQuery(){
//
//        $notes = "应用" . $this->client_id . "，调用用户地址查询接口";
//
//        addLog("User/addressQuery", $_GET, $_POST, $notes);
//
//        $this->checkVersion(100);
//
//        if(IS_POST){
//            $uid = $this->_post('uid',0,'用户ID缺失');
//
//            $map['uid'] = $uid;
//            $order = 'id asc';
//            $result = apiCall(AddressApi::QUERY_NO_PAGING,array($map,$order));
//
//            if(!$result['status']){
//                $this->apiReturnErr($result['info']);
//            }else{
//                $this->apiReturnSuc($result['info']);
//            }
//
//        }else{
//            $this->apiReturnErr("只支持POST请求!");
//        }
//
//    }
//
//    /**
//     * 用户地址删除
//     */
//    public function addressDelete(){
//
//        $notes = "应用" . $this->client_id . "，调用用户地址删除接口";
//
//        addLog("User/addressDelete", $_GET, $_POST, $notes);
//
//        $this->checkVersion(100);
//
//        if(IS_POST){
//
//            $id = $this->_post('id',0,'id缺失');
//
//            $map['id'] = $id;
//            $result = apiCall(AddressApi::DELETE,array($map));
//
//            if(!$result['status']){
//                $this->apiReturnErr($result['info']);
//            }else{
//                $this->apiReturnSuc('删除成功');
//            }
//
//        }else{
//            $this->apiReturnErr("只支持POST请求!");
//        }
//
//    }
//
   /**
    * 检查这些参数是否合法
    * @param $type
    * @param $username
    * @param $from
    * @return bool|string
    */
   private function isLegal($type,$username,$from){

       //TODO: 检查from的值是否合法
       //TODO: 检测用户账号是否合法
       //1. $type = 1 的时候 $username 是用户名
       //2. $type = 2 的时候 $username 是邮箱,应该符合邮箱规则
       //3. $type = 4 的时候 $username 是手机,应该符合手机的规则
       $from = intval($from);

       if(!OAuth2Type::checkType($from)) return "用户来源参数无效";

       if($type == UcenterMember::ACCOUNT_TYPE_MOBILE && $this->getUsernameType($username) != $type){
           //$this->apiReturnErr($type." ".$this->getUsernameType($username))    ;
           $this->apiReturnErr("手机号非法!");
       }

       $notes=  "检测用户名:".$username."来源";

       $result =  apiCall(UserApi::CHECK_USER_NAME,array($username));

       if(!$result['status']) return "用户名已被注册!";

       $result = apiCall(UserApi::CHECK_MOBILE,array($username));
       if(!$result['status']) return "手机号已被注册";

       APP_DEBUG && trace("isLegal",$result,"",$notes);

       return false;

   }

   /**
    * 更新用户手机号
    * @param $uid
    * @param $mobile
    */
   private function updateMobile($uid,$mobile){

       $entity = ['phone_validate'=>1];

       $result = apiCall(UserApi::SAVE_BY_ID,[$uid,['mobile'=>$mobile]]);
       if($result['status']){
           $result = apiCall(MemberConfigApi::SAVE_BY_ID,[$uid,$entity]);
           if($result['status']){
              $r = apiCall(UserApi::GET_INFO,[$uid]);
              if(!$r['status']) $this->apiReturnErr($r['info']);
              $this->apiReturnSuc($r['info']);
              // $this->apiReturnSuc("绑定成功!");
           }else{
               $this->apiReturnErr($result['info']);
           }
       }else{
           $this->apiReturnErr($result['info']);
       }
   }

   /**
    * 检测登录账户的类型
    * 3: 手机号
    * 2: EMAIL
    * @param $str
    * @return int
    */
    private function getUsernameType($str){

        if(preg_match("/^1\d{10}$/",$str)){
            return UcenterMember::ACCOUNT_TYPE_MOBILE;
        }

        return UcenterMember::ACCOUNT_TYPE_USERNAME;
    }
    public function __construct(){
      parent::__construct();
    }
}